// notifications.js
import { userApi } from '../../../services/api';
import { formatTimeAgo } from '../../../utils/util';

const NOTIFICATION_STORAGE_KEY = 'sj_user_notifications';
const LAST_VISIT_TIME_KEY = 'sj_notifications_last_visit';

Page({
  data: {
    notifications: [],
    loading: true
  },
  
  onLoad() {
    // 先标记缓存中的通知为已读，再加载新数据
    this.markAllCachedAsRead();
    this.loadNotifications();
  },
  
  onShow() {
    // 如果不是首次加载，则刷新数据
    if (this.data.notifications.length > 0) {
      this.loadNotifications();
    }
  },
  
  onHide() {
    // 用户离开页面时，记录当前时间
    wx.setStorageSync(LAST_VISIT_TIME_KEY, new Date().getTime());
  },
  
  onUnload() {
    // 用户离开页面时，记录当前时间
    wx.setStorageSync(LAST_VISIT_TIME_KEY, new Date().getTime());
  },
  
  onPullDownRefresh() {
    this.loadNotifications().then(() => {
      wx.stopPullDownRefresh();
    });
  },
  
  // 返回上一页
  navigateBack() {
    wx.navigateBack();
  },
  
  // 将缓存中的所有通知标记为已读
  markAllCachedAsRead() {
    try {
      const localData = wx.getStorageSync(NOTIFICATION_STORAGE_KEY);
      if (!localData) return;
      
      const localNotifications = JSON.parse(localData);
      if (!localNotifications || localNotifications.length === 0) return;
      
      // 将所有缓存通知标记为已读
      const markedNotifications = localNotifications.map(item => ({
        ...item,
        isRead: true
      }));
      
      // 保存回缓存
      wx.setStorageSync(NOTIFICATION_STORAGE_KEY, JSON.stringify(markedNotifications));
    } catch (error) {
      console.error('标记缓存通知已读失败', error);
    }
  },
  
  // 加载消息通知列表
  async loadNotifications() {
    this.setData({ loading: true });
    
    try {
      // 1. 从本地存储获取已缓存通知（已全部标记为已读）
      const localNotifications = this.getLocalNotifications();
      
      // 2. 从服务器获取新通知
      const serverNotifications = await this.fetchServerNotifications();
      
      // 3. 合并服务器通知到本地缓存（保持服务器通知为未读状态）
      const mergedNotifications = this.mergeNotifications(serverNotifications, localNotifications);
      
      // 4. 更新所有通知的时间显示
      const notificationsWithUpdatedTime = mergedNotifications.map(item => ({
        ...item,
        createDateStr: formatTimeAgo(item.originalDateStr || item.createDateStr)
      }));
      
      // 5. 更新视图
      this.setData({
        notifications: notificationsWithUpdatedTime,
        loading: false
      });
      
      return Promise.resolve();
    } catch (error) {
      console.error('加载通知失败', error);
      wx.showToast({
        title: '加载通知失败',
        icon: 'none'
      });
      this.setData({ loading: false });
      return Promise.reject(error);
    }
  },
  
  // 从服务器获取未读通知
  fetchServerNotifications() {
    return new Promise((resolve, reject) => {
      userApi.noticeList()
        .then(res => {
          if (res.status === 200 && res.data) {
            // 将服务器通知标记为未读并处理时间显示
            const serverNotifications = (res.data || []).map(item => {
              // 保存原始时间字符串
              const originalDateStr = item.createDateStr;
              
              return {
                ...item,
                isRead: false,
                fromServer: true,
                fetchTime: new Date().getTime(),
                // 保存原始时间字符串用于后续更新
                originalDateStr: originalDateStr,
                // 格式化时间显示
                createDateStr: formatTimeAgo(originalDateStr)
              };
            });
            resolve(serverNotifications);
          } else {
            reject(new Error('获取通知失败'));
          }
        })
        .catch(reject);
    });
  },
  
  // 从本地存储获取已缓存通知
  getLocalNotifications() {
    try {
      const localData = wx.getStorageSync(NOTIFICATION_STORAGE_KEY) || '[]';
      return JSON.parse(localData);
    } catch (error) {
      console.error('获取本地通知失败', error);
      return [];
    }
  },
  
  // 合并新通知到本地缓存并保存
  mergeNotifications(serverNotifications, localNotifications) {
    if (!serverNotifications || serverNotifications.length === 0) {
      return localNotifications;
    }
    
    let updatedNotifications = [...localNotifications];
    // 倒叙serverNotifications
    serverNotifications.reverse();
    // 遍历新通知，如果本地缓存中不存在，则添加
    serverNotifications.forEach(newNotice => {
      const existingIndex = updatedNotifications.findIndex(local => local.id === newNotice.id);
      if (existingIndex === -1) {
        // 新通知，直接添加
        updatedNotifications.unshift(newNotice);
      }
    });
    
    this.saveNotificationsToLocal(updatedNotifications);
    return updatedNotifications;
  },
  
  // 保存通知到本地存储
  saveNotificationsToLocal(notifications) {
    try {
      wx.setStorageSync(NOTIFICATION_STORAGE_KEY, JSON.stringify(notifications));
    } catch (error) {
      console.error('保存通知到本地失败', error);
    }
  },
  
  // 查看通知，将未读标记为已读
  viewNotification(e) {
    const { id } = e.currentTarget.dataset;
    
    // 标记通知为已读
    this.markAsRead(id);
  },
  
  // 查看通知详情，跳转到目标URL
  viewDetail(e) {
    const { id } = e.currentTarget.dataset;
    const { notifications } = this.data;
    
    // 找到当前通知
    const currentNotification = notifications.find(item => item.id === id);
    if (!currentNotification || !currentNotification.targetUrl) return;
    
    // 标记为已读
    this.markAsRead(id);
    
    // 跳转到目标URL
    wx.navigateTo({
      url: currentNotification.targetUrl
    });
  },
  
  // 标记通知为已读
  markAsRead(id) {
    const { notifications } = this.data;
    const currentNotification = notifications.find(item => item.id === id);
    
    // 如果通知不存在或已读，则不处理
    if (!currentNotification || currentNotification.isRead) return;
    
    // 1. 更新视图中的已读状态
    const updatedNotifications = notifications.map(item => {
      if (item.id === id) {
        return { ...item, isRead: true };
      }
      return item;
    });
    
    this.setData({ notifications: updatedNotifications });
    
    // 2. 更新本地存储中的已读状态
    const localNotifications = this.getLocalNotifications();
    const updatedLocalNotifications = localNotifications.map(item => {
      if (item.id === id) {
        return { ...item, isRead: true };
      }
      return item;
    });
    
    this.saveNotificationsToLocal(updatedLocalNotifications);
  },
  
  // 删除通知
  deleteNotification(e) {
    const { id } = e.currentTarget.dataset;
    const { notifications } = this.data;
    
    // 从列表中移除通知
    const updatedNotifications = notifications.filter(item => item.id !== id);
    this.setData({ notifications: updatedNotifications });
    
    // 从本地存储中删除
    const localNotifications = this.getLocalNotifications();
    const updatedLocalNotifications = localNotifications.filter(item => item.id !== id);
    this.saveNotificationsToLocal(updatedLocalNotifications);
    
    wx.showToast({
      title: '删除成功',
      icon: 'success'
    });
  }
}) 